// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()

const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const _openid = wxContext.OPENID

  switch (event.action) {
    case 'checkPostComment': {
      return checkPostComment(event)
    }
    case 'addPostComment': {
      return addPostComment(event, _openid)
    }
    case 'addPostChildComment': {
      return addPostChildComment(event, _openid)
    }
    default: break
  }

}
/**
 * 接入内容安全
 * @param {} event 
 */
async function checkPostComment(event) {

  try {
    let result = await cloud.openapi.security.msgSecCheck({
      content: event.content
    })
    if (result.errCode == 0) {
      return true;
    }
    return false
  } catch (err) {
    return false;
  }
}

/**
 * 新增评论
 * @param {} event 
 */
async function addPostComment(event, _openid) {
  console.info("处理addPostComment")
  let task = db.collection('blog').doc(event.commentContent.postId).update({
    data: {
      commentNum: _.inc(1)
    }
  });
  event.commentContent.flag = 0
  await db.collection("blog-comment").add({
    data: {
      ...event.commentContent,
      createTime: db.serverDate(), // 服务端的时间
      _openid
      }
  });
  let result = await task;
}

/**
 * 新增子评论
 * @param {} event 
 */
async function addPostChildComment(event, _openid) {
  let task = db.collection('blog').doc(event.postId).update({
    data: {
      commentNum: _.inc(1)
    }
  });
  event.comments[0].flag = 0
  await db.collection('blog-comment').doc(event.id).update({
    data: {
      childComment: _.push(event.comments),
      createTime: db.serverDate(), // 服务端的时间
      _openid
    }
  })
  await task;
}